// stores/knowledge.ts
import { defineStore } from 'pinia'

export interface KnowledgePoint {
  id: string
  title: string
  category: string
  type: 'danger' | 'warning' | 'success'
}

export const useKnowledgeStore = defineStore('knowledge', {
  state: () => ({
    knowledgePoints: [] as KnowledgePoint[]
  }),
  actions: {
    loadKnowledgePoints() {
      // 动态加载所有知识点文件
      const vue3Files = import.meta.glob('@/views/Knowledge/vue3/*.vue', { eager: true })
      const cssFiles = import.meta.glob('@/views/Knowledge/css/*.vue', { eager: true })

      // 将 vue3 和 css 目录下的文件合并为知识点
      const loadedPoints = [
        ...this.createKnowledgePoints(vue3Files, 'vue3'),
        ...this.createKnowledgePoints(cssFiles, 'css')
      ]

      // 从 localStorage 加载已保存的掌握程度
      const savedTypes = JSON.parse(localStorage.getItem('knowledgeTypes') || '{}')

      // 更新 knowledgePoints，应用保存的掌握程度
      this.knowledgePoints = loadedPoints.map((point) => ({
        ...point,
        type: savedTypes[point.id] || point.type // 从 localStorage 获取掌握程度
      }))
    },
    createKnowledgePoints(files: Record<string, any>, category: string): KnowledgePoint[] {
      return Object.keys(files).map((filePath) => {
        const id = filePath.split('/').pop()?.replace('.vue', '') || ''
        return {
          id,
          title: this.generateTitle(id), // 使用自定义方法生成标题
          category, // 从路径推断 category
          type: 'danger' // 默认掌握程度设置为 'danger'
        }
      })
    },
    setKnowledgeType(id: string, type: 'danger' | 'warning' | 'success') {
      const point = this.knowledgePoints.find((p) => p.id === id)
      if (point) {
        point.type = type

        // 保存掌握程度到 localStorage
        const savedTypes = JSON.parse(localStorage.getItem('knowledgeTypes') || '{}')
        savedTypes[id] = type
        localStorage.setItem('knowledgeTypes', JSON.stringify(savedTypes))
      }
    },
    generateTitle(id: string): string {
      // 将 camelCase 或其他命名转换为可读标题
      return id.replace(/([A-Z])/g, ' $1').trim()
    }
  }
})
